<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

class igphotoModelIgphoto extends igbaseModel
{
    protected $context = 'igphoto';
	protected $tablename = 'igallery_img';
	protected $filterOrderDefault = 'ordering';
	
	function __construct($task)
	{
		parent::__construct();
		$this->reorderClause = 'gallery_id = '.(int)$this->_catid;
    }
	
	function _buildQuery()
	{
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();
        
        $query = 'SELECT '.
		'#__igallery_img.*, '.
		'#__igallery.name, '.
		'#__igallery_profiles.max_width, #__igallery_profiles.max_height, #__igallery_profiles.thumb_width, '.
		'#__igallery_profiles.thumb_height, #__igallery_profiles.crop_thumbs, #__igallery_profiles.img_quality, '.
		'#__igallery_profiles.watermark, #__igallery_profiles.watermark_filename, #__igallery_profiles.watermark_position, '.
		'#__igallery_profiles.watermark_transparency, #__igallery_profiles.crop_main, #__igallery_profiles.crop_lbox, '.
        '#__igallery_profiles.round_large, #__igallery_profiles.round_thumb, #__igallery_profiles.round_fill, '.
        '#__igallery_profiles.watermark_text, #__igallery_profiles.watermark_text_color, #__igallery_profiles.watermark_text_size '.
		'FROM #__igallery_img '.
		'INNER JOIN #__igallery ON #__igallery.id = #__igallery_img.gallery_id '.
		'INNER JOIN #__igallery_profiles ON #__igallery_profiles.id = #__igallery.profile '.
		$where . $orderby;
		
		return $query;
	}
	
	function _buildContentWhere()
	{
		global $mainframe, $option;
		
		$catid		        = $mainframe->getUserStateFromRequest( $this->context.'.catid',		        'catid',		    0,				'int' );
		$filter_state		= $mainframe->getUserStateFromRequest( $this->context.'.filter_state',		'filter_state',		'',				'word' );
		$filter_order		= $mainframe->getUserStateFromRequest( $this->context.'.filter_order',		'filter_order',		'ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $this->context.'.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$search				= $mainframe->getUserStateFromRequest( $this->context.'.search',			    'search',			'',				'string' );
		$search				= JString::strtolower( $search );

		$where = array();
		$searchArray = array();
		if( !empty($catid) )
		{
        	$where[] = 'gallery_id = '.(int) $catid;
		}
		
        if ($search) 
		{
		    $searchArray[] = 'description LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
			$searchArray[] = 'filename LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
			$searchArray[] = 'tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
			$searchArray[] = 'alt_text LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
			$searchClauses = implode( ' OR ', $searchArray ) ;
			$where[] = '('.$searchClauses.')';
		}
		
		if ($filter_state) 
		{
			if ( $filter_state == 'P' ) 
			{
				$where[] = '#__igallery_img.published = 1';
			} 
			else if ($filter_state == 'U' ) 
			{
				$where[] = '#__igallery_img.published = 0';
			}
		}

		$where 		= ( count( $where ) ? ' WHERE '. implode( ' AND ', $where ) : '' );

		return $where;
	}
	
	function getDataFrontend()
	{
	    $query = 'SELECT * from #__igallery_img WHERE gallery_id = '.(int)$this->_catid.' ORDER BY ordering';
    	$this->_db->setQuery($query);
    	$this->_data = $this->_db->loadObjectlist();
		
    	$count = count($this->_data);
    	
		for($i=0; $i<$count; $i++ )
		{
			if( !$this->authenticate('acl_photo_view', $this->_data[$i]->id) )
			{
				unset($this->_data[$i]);
			}
		}
		$this->_data = array_values($this->_data);
    	
    	return $this->_data;
	}
    
    function save($post)
	{
	    $row =& $this->getTable('igallery_img');
	    
	    $row->id = $this->_id;
	    if (!$row->bind($post)) 
		{
			JError::raise(2, 500, $this->_db->getErrorMsg());
			return false;
		}

		$row->description = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWHTML );
		$row->alt_text = htmlspecialchars($row->alt_text, ENT_QUOTES);

		if (!$row->store()) 
		{
			JError::raise(2, 500, $this->_db->getErrorMsg());
			return false;
		}
		
		$query = 'SELECT gallery_id, ordering from #__igallery_img WHERE id = '.(int)$this->_id;
    	$this->_db->setQuery($query);
    	$currentRow = $this->_db->loadObject();
		
		$nextOrdering = $currentRow->ordering + 1;
		$query = 'SELECT id from #__igallery_img WHERE gallery_id = '.(int)$currentRow->gallery_id.' AND ordering = '.(int)$nextOrdering.' LIMIT 1';
    	$this->_db->setQuery($query);
    	$nextRow = $this->_db->loadObject();
    	
		return $nextRow->id;
	}
	
	function store($fileData)
	{
	    $row =& $this->getTable('igallery_img');
		$user =& JFactory::getUser();
		$configArray =& JComponentHelper::getParams('com_igallery');
		
		$row->id = null;
        $row->user = $user->id;
		$row->target_blank = $configArray->get('target_blank', 1);
		$row->access = $configArray->get('new_image_access', 0);
		$row->published = $configArray->get('new_image_published', 1);
		$row->gallery_id = (int)$this->_catid;
		$row->filename = $fileData['filename'];
		$row->moderate = $configArray->get('moderate_img', 0) == 0 || IG_BACKEND == true ? 1 : 0;

		$firstLast = $configArray->get('new_image_ordering', 'last');
		$row->ordering = $firstLast == 'first' ? 0 : $row->getNextOrder('gallery_id = '.(int)$this->_catid );
		
		if( isset($fileData['exif_des']) )
		{
			$row->description = strlen($fileData['exif_des']) > 0 ? $fileData['exif_des'] : $row->description;
		}
		
		if( isset($fileData['iptc_des']) )
		{
			$row->description = strlen($fileData['iptc_des']) > 0 ? $fileData['iptc_des'] : $row->description;
		}
				
        if( !$row->store() )
		{
		  	echo $row->getError();
		  	return false;
		}

		//if the image was added to the start of the order, we need to reorder
		if($firstLast == 'first')
	    {
	       $row->reorder('gallery_id = '.(int)$this->_catid );
	    }
	    
	    $mainframe =& JFactory::getApplication();
	    $sessionValue = $mainframe->getUserState('com_igallery.moderateimg'.$row->gallery_id, 0);
	   
	    if(IG_BACKEND == false && empty($sessionValue) )
	    {
			if($configArray->get('notify_new_image', 0) == 1)
			{
				$this->notify('image', $row->id);
				
				$mainframe->setUserState( 'com_igallery.moderateimg'.$row->gallery_id, 1);
			}
	    }
	    
	    return true;
	}
	
	function remove()
	{
	    $cid = JRequest::getVar( 'cid', array(), '', 'array' );
		JArrayHelper::toInteger($cid);
		
		for($i=0; $i<count($cid); $i++)
		{
		    $query = 'SELECT filename FROM #__igallery_img WHERE id = '.(int)$cid[$i];
            $this->_db->setQuery($query);
            $this->_photo = $this->_db->loadObject();
		
    		$query = 'SELECT filename FROM #__igallery_img WHERE filename = '.$this->_db->Quote($this->_photo->filename);
    		$this->_db->setQuery($query);
    		$this->_db->query();
    		$numRows = $this->_db->getNumRows();
    		$deleteOrig = $numRows > 1 ? false: true;
    		
    	    igFileHelper::deleteImage($this->_photo->filename, $deleteOrig);
		    
    		//delete the comments for this photo
    		$query = 'DELETE FROM #__igallery_comments WHERE img_id = '.(int)$cid[$i];
    		$this->_db->setQuery($query);
    		if(!$this->_db->query())
    		{
    			$this->setError($this->_db->getErrorMsg());
    			return false;
    		}
            
    		
    		//delete the ratings for this photo
    		$query = 'DELETE FROM #__igallery_rating WHERE img_id = '.(int)$cid[$i];
    		$this->_db->setQuery($query);
    
    		if(!$this->_db->query())
    		{
    			$this->setError($this->_db->getErrorMsg());
    			return false;
    		}
            
    		//delete the photo row(s)
    		$query = 'DELETE FROM #__igallery_img WHERE id = '.(int)$cid[$i];
    		$this->_db->setQuery($query);
    		if(!$this->_db->query())
    		{
    			$this->setError($this->_db->getErrorMsg());
    			return false;
    		}
    		
		}
		
		$row =& $this->getTable('igallery_img');
    	$row->reorder('gallery_id = '.(int)$this->_catid );
		
		return true;
	}
	
	function copy_move()
	{
	    $targetCat = JRequest::getInt('cat_id_copy_move');
	    if($targetCat == 0)
        {
            JError::raise(2, 500, JText::_('NO TARGET CATEGORY SELECTED') ); 
        }
        
        $cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		
		$copyMove = JRequest::getWord('copy_move','copy');
		
		
        for($i=0; $i<count($cid); $i++)
		{
			$row =& $this->getTable('igallery_img');
            $row->load($cid[$i]);
            $origId = $row->id;
            
            $row->id = null;
            $row->gallery_id = (int)$targetCat;
            $row->ordering = $row->getNextOrder('gallery_id = '.(int)$targetCat );
		   
            if(!$row->store())
            {
               $this->setError($this->_db->getErrorMsg());
               return false;
            }
            
            $newId = $row->id;
            
            //move comments
            $row =& $this->getTable('igallery_comments');
            
			$query = 'SELECT * FROM #__igallery_comments WHERE img_id = '.(int)$origId;
	        $this->_db->setQuery($query);
	        $rows = $this->_db->loadObjectList();
	        
	        if( count($rows) )
	        {
		        for($i=0; $i<count($rows); $i++)
		        {
		        	$row->load($rows[$i]->id);
		        	$row->id = null;
		        	$row->img_id = (int)$newId;
		        	$row->gallery_id = (int)$targetCat;
			        if(!$row->store())
		            {
		               $this->setError($this->_db->getErrorMsg());
		               return false;
		            }
		        }
	        }
	        
			//move ratings
            $row =& $this->getTable('igallery_rating');
            
			$query = 'SELECT * FROM #__igallery_rating WHERE img_id = '.(int)$origId;
	        $this->_db->setQuery($query);
	        $rows = $this->_db->loadObjectList();
	        
	        if( count($rows) )
	        {
		        for($i=0; $i<count($rows); $i++)
		        {
		        	$row->load($rows[$i]->id);
		        	$row->id = null;
		        	$row->img_id = (int)$newId;
		        	$row->gallery_id = (int)$targetCat;
			        if(!$row->store())
		            {
		               $this->setError($this->_db->getErrorMsg());
		               return false;
		            }
		        }
	        }
	        
            
            if($copyMove == 'move')
            {
                $query = 'DELETE FROM #__igallery_img WHERE id = '.(int)$origId;
        		$this->_db->setQuery($query);
        		if(!$this->_db->query())
        		{
        			$this->setError($this->_db->getErrorMsg());
        			return false;
        		}
        		
            	$query = 'DELETE FROM #__igallery_comments WHERE img_id = '.(int)$origId;
        		$this->_db->setQuery($query);
        		if(!$this->_db->query())
        		{
        			$this->setError($this->_db->getErrorMsg());
        			return false;
        		}
        		
            	$query = 'DELETE FROM #__igallery_rating WHERE img_id = '.(int)$origId;
        		$this->_db->setQuery($query);
        		if(!$this->_db->query())
        		{
        			$this->setError($this->_db->getErrorMsg());
        			return false;
        		}
            }
		}
		return true;
	}
	
	function rotate()
	{
		$id = JRequest::getInt('id', 0);
		$rvalue = JRequest::getInt('rvalue', 0);
		
		$row =& $this->getTable('igallery_img');
		$row->load( (int)$id );
		
		if($rvalue == 0)
		{
			if($row->rotation == 0)
			{
				$row->rotation = 270;
			}
			else
			{
				$row->rotation = $row->rotation - 90;
			}
		}
		else
		{
			if($row->rotation == 270)
			{
				$row->rotation = 0;
			}
			else
			{
				$row->rotation = $row->rotation + 90;
			}
		}
		
		if (!$row->store()) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		return true;
	}
	
	function addHit($id)
	{
		$row =& $this->getTable('igallery_img');
		$row->load( (int)$id );
		$row->hits = $row->hits + 1;
		if(!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
	
	function assignMenuImage()
	{
		$id = JRequest::getInt('id', 0);
		$catid = JRequest::getInt('catid', 0);
		$cvalue = JRequest::getInt('cvalue', 0);
		
		$query = 'UPDATE #__igallery_img SET menu_image = 0 WHERE gallery_id = '.(int)$catid;
		$this->_db->setQuery($query);
		if(!$this->_db->query())
    	{
    		$this->setError($this->_db->getErrorMsg());
    		return false;
    	}
    	
		$query = 'UPDATE #__igallery_img SET menu_image = '.(int)$cvalue.' WHERE id = '.(int)$id;
		$this->_db->setQuery($query);
		if(!$this->_db->query())
    	{
    		$this->setError($this->_db->getErrorMsg());
    		return false;
    	}
		
    	return true;
	}
	
	function reportImage()
	{
		$id = JRequest::getInt('id', 0);
		$text = JRequest::getVar('report_textarea', '');
		$this->notify('report', $id, $text);
		return true;
	}
	
	function move($direction)
	{
		$row =& $this->getTable($this->tablename);
		if (!$row->load($this->_id)) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->move($direction) ) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		$row->reorder('gallery_id = '.(int)$row->gallery_id);

		return true;
	}
}